package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.UserRelationDao;
import com.jbp.exception.RRException;
import com.jbp.model.User;
import com.jbp.model.UserRelation;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.UserRelationService;
import com.jbp.service.UserService;
import com.jbp.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户关系(UserRelation)表服务实现类
 * @author cc
 * @since 2020-06-21 12:06:02
 */
@Service
public class UserRelationServiceImpl extends ServiceImpl<UserRelationDao, UserRelation> implements UserRelationService {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisConfigService redisConfigService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserRelation> page = this.page(
                new Query<UserRelation>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**关注*/
    @Override
    @Transactional
    public void follow(Integer userId, Integer friendId) {
        ///检查是否已经关注
        UserRelation relationFrom = getByUserAndFriendId(userId, friendId);
        if (relationFrom!=null && (relationFrom.getStatus()==1 || relationFrom.getStatus()==2)) {
            throw new RRException("已经关注过啦");
        }

        ///修改关注者状态
        if (relationFrom==null) {
            relationFrom = new UserRelation();
            relationFrom.setUserId(userId);
            relationFrom.setFriendId(friendId);
            relationFrom.setStatus(2);
            save(relationFrom);
        } else {
            if(relationFrom.getStatus()==0) {
                //未关注改为已关注
                relationFrom.setStatus(2);
            } else if(relationFrom.getStatus()==3) {
                //粉丝改为好友
                relationFrom.setStatus(1);
            }
            updateById(relationFrom);
        }

        ///修改被关注者状态
        UserRelation relationTo = getByUserAndFriendId(friendId, userId);
        if (relationTo==null) {
            relationTo = new UserRelation();
            relationTo.setUserId(friendId);
            relationTo.setFriendId(userId);
            relationTo.setStatus(3);
            save(relationTo);
        } else {
            if(relationTo.getStatus()==0) {
                //无改为粉丝
                relationTo.setStatus(3);
            } else if(relationTo.getStatus()==2) {
                //关注改为好友
                relationTo.setStatus(1);
            }
            updateById(relationTo);
        }
    }

    /**取消关注*/
    @Override
    @Transactional
    public void unFollow(Integer userId, Integer friendId) {
        ///修改关注者状态
        UserRelation relationFrom = getByUserAndFriendId(userId, friendId);
        if (relationFrom!=null) {
            if (relationFrom.getStatus()==1) {
                //好友改为粉丝
                relationFrom.setStatus(3);
            } else if (relationFrom.getStatus()==2) {
                //已关注改为未关注
                relationFrom.setStatus(0);
            }
            updateById(relationFrom);
        }

        ///修改被关注者状态
        UserRelation relationTo = getByUserAndFriendId(friendId, userId);
        if (relationTo!=null) {
            if(relationTo.getStatus()==3) {
                //粉丝改为无
                relationTo.setStatus(0);
            } else if(relationTo.getStatus()==1) {
                //好友改为关注
                relationTo.setStatus(2);
            }
            updateById(relationTo);
        }
    }

    //拉黑/取消拉黑
    @Override
    public void lahei(Integer userId, UserRelation req) {
        UserRelation relationFrom = getByUserAndFriendId(userId, req.getFriendId());
        ///修改关注者状态
        if (relationFrom==null) {
            relationFrom = new UserRelation();
            relationFrom.setUserId(userId);
            relationFrom.setFriendId(req.getFriendId());
            relationFrom.setBlack(req.getBlack());
            save(relationFrom);
        } else {
            relationFrom.setBlack(req.getBlack());
            updateById(relationFrom);
        }
    }

    @Override
    public PageUtils blackList(Map<String, Object> params) {
        QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id", params.get("userId"));
        queryWrapper.eq("black",1);
        queryWrapper.orderByDesc("update_time");

        IPage<UserRelation> page = this.page(
                new Query<UserRelation>().getPage(params),
                queryWrapper
        );

        List<User> userList = page.getRecords().stream()
                .map((userRelation)->{
                    User user = userService.getById(userRelation.getFriendId());
                    user.setPassword("");
                    user.setSalt("");
                    Object object = redisConfigService.get(Constant.ROOM_PREFIX+user.getId());
                    if (object == null) {
                        user.setIsOnline("offline");
                    }
                    if (userRelation==null) {
                        user.setFriendStatus(0);
                    } else {
                        user.setFriendStatus(userRelation.getStatus());
                    }
                    user.setBlack(userRelation.getBlack());
                    return user;
                })
                .collect(Collectors.toList());

        return new PageUtils(userList, (int) page.getTotal(), (int)page.getPages(),(int)page.getCurrent());
    }

    @Override
    public UserRelation getByUserAndFriendId(Integer userId, Integer friendId) {
        QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("friend_id", friendId);
        return  getOne(queryWrapper);
    }

    @Override
    public PageUtils friendList(Map<String, Object> params) {
        QueryWrapper<UserRelation> queryWrapper = new QueryWrapper<>();

        //好友状态
        Object statusParam = params.get("status");
        if (statusParam != null && !statusParam.equals("")){
            if ("3".equals(statusParam)) {
                queryWrapper.in("status", 1, 3);
            } else if ("2".equals(statusParam)) {
                queryWrapper.in("status", 1, 2);
            } else {
                queryWrapper.eq("status", statusParam);
            }
        }

        //uuid或昵称搜索
        if (params.get("name") != null && !params.get("name").equals("")){
            queryWrapper.inSql("friend_id", "select id from user WHERE name LIKE '%"+params.get("name")+"%' OR uuid LIKE '%"+params.get("name")+"%'");
        }



        queryWrapper.eq("user_id", params.get("userId"));
        queryWrapper.orderByDesc("update_time");

        IPage<UserRelation> page = this.page(
                new Query<UserRelation>().getPage(params),
                queryWrapper
        );

        List<User> userList = page.getRecords().stream()
                .map((userRelation)->{
                    User user = userService.getById(userRelation.getFriendId());
                    user.setPassword("");
                    user.setSalt("");
                    Object object = redisConfigService.get(Constant.ROOM_PREFIX+user.getId());
                    if (object == null) {
                        user.setIsOnline("offline");
                    }
                    if (userRelation==null) {
                        user.setFriendStatus(0);
                        user.setBlack(0);
                    } else {
                        user.setFriendStatus(userRelation.getStatus());
                        user.setBlack(userRelation.getBlack());
                    }
                    return user;
                })
                .filter(user -> {
                    //在线
                    if ("online".equals(params.get("isOnline"))){
                        Object object = redisConfigService.get(Constant.ROOM_PREFIX+user.getId());
                        if (object == null) {
                            return false;
                        }
                    }
                    return true;
                })
                .collect(Collectors.toList());



        return new PageUtils(userList, (int) page.getTotal(), (int)page.getPages(),(int)page.getCurrent());
    }


}